package com.accelstack.cmp.security;

import com.accelstack.cmp.entity.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * Session管理服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SessionService {
    
    private final RedisTemplate<String, Object> redisTemplate;
    
    private static final String SESSION_USER_KEY = "user";
    private static final String SESSION_LOGIN_TIME_KEY = "loginTime";
    private static final String SESSION_IP_KEY = "ip";
    
    /**
     * 创建用户Session
     */
    public void createSession(HttpServletRequest request, User user) {
        HttpSession session = request.getSession(true);
        
        // 存储用户信息到Session
        session.setAttribute(SESSION_USER_KEY, user.getUsername());
        session.setAttribute(SESSION_LOGIN_TIME_KEY, System.currentTimeMillis());
        session.setAttribute(SESSION_IP_KEY, getClientIp(request));
        
        log.info("Session创建成功 - 用户: {}, SessionId: {}", user.getUsername(), session.getId());
    }
    
    /**
     * 获取当前用户
     */
    public String getCurrentUser(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return null;
        }
        return (String) session.getAttribute(SESSION_USER_KEY);
    }
    
    /**
     * 销毁Session
     */
    public void destroySession(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            String username = (String) session.getAttribute(SESSION_USER_KEY);
            session.invalidate();
            log.info("Session已销毁 - 用户: {}", username);
        }
    }
    
    /**
     * 获取Session信息
     */
    public Map<String, Object> getSessionInfo(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        Map<String, Object> info = new HashMap<>();
        
        if (session == null) {
            info.put("active", false);
            return info;
        }
        
        info.put("active", true);
        info.put("sessionId", session.getId());
        info.put("username", session.getAttribute(SESSION_USER_KEY));
        info.put("loginTime", session.getAttribute(SESSION_LOGIN_TIME_KEY));
        info.put("ip", session.getAttribute(SESSION_IP_KEY));
        info.put("creationTime", session.getCreationTime());
        info.put("lastAccessedTime", session.getLastAccessedTime());
        info.put("maxInactiveInterval", session.getMaxInactiveInterval());
        
        return info;
    }
    
    /**
     * 延长Session有效期
     */
    public void refreshSession(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.setMaxInactiveInterval(1800); // 30分钟
        }
    }
    
    /**
     * 获取客户端IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 处理多个IP的情况（取第一个）
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }
    
    /**
     * 统计在线用户数
     */
    public long getOnlineUserCount() {
        // 通过Redis统计活跃Session数量
        String pattern = "spring:session:sessions:*";
        return redisTemplate.keys(pattern).size();
    }
}

